package com.infindo.frame.data.net;

import java.io.BufferedReader;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.InterruptedIOException;
import java.io.OutputStream;
import java.io.UnsupportedEncodingException;
import java.net.HttpURLConnection;
import java.net.URL;

import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.InputStreamEntity;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.params.BasicHttpParams;
import org.apache.http.params.HttpConnectionParams;
import org.apache.http.params.HttpParams;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

 
import android.content.Context;
import android.util.Log;
import android.widget.Toast;

import com.infindo.frame.data.DataHandler;
import com.infindo.frame.data.DataProcessor;
import com.infindo.frame.data.mo.MoliscMessage;
import com.infindo.frame.data.mo.SystemError;
import com.infindo.frame.util.JSONUtil;
 
import com.tiantian.app.manager.Const;
import com.tiantian.app.manager.DataModel;

@SuppressWarnings("unused")
public class RequestPost extends DataHandler {
	private String tag = "requestPost";
	private static final String ENCODE = "UTF-8";
	private String url;
	private String data;
	private DataProcessor dataProc;
	private String type;
	private Context context;

	public RequestPost(Context context,String url, String data, String type, boolean isNeedTimer, DataProcessor dataProc, int dataHandlerNo, CallbackListener listener) {
		super(dataHandlerNo, listener);
		this.setBolNeedTimer(isNeedTimer);
		this.context = context;
		this.url = url;
		this.data = data;
		this.type = type;
		this.dataProc = dataProc;
	}

	public void start() {
		new Thread(this).start();
	}

	public void run() {
		Object result = null;
		try {
			result = post(data, url);
			if(result instanceof JSONObject){
				  JSONObject json = (JSONObject)result;
				  Log.e(tag,"result:"+json.toString());
				  String clazz = json.getString("clazz");
				  result = (MoliscMessage)JSONUtil.convertToBean(json,clazz,true);
				  if(result instanceof SystemError){
					    SystemError se = (SystemError)result;
					    Toast.makeText(context, se.getTitle()+":"+se.getMessage(), Toast.LENGTH_SHORT).show();
				  }
					  
			}
		} catch (Throwable e) {
			result = e;
		}
		if (this.dataProc.checkNoCancelQueue(super.getDataHandlerNo())) {
			this.getCallbackListener().callback(type,0,result);
		}
	}

    public Object post(String content, String url) {
		InputStream in = null;
		OutputStream out = null;
		ByteArrayOutputStream bos = null;
		Log.i(tag,"url:"+url);
		Log.i(tag, "req:" + content);
	
		try {
			byte[] postdata = content.getBytes(ENCODE);
			HttpParams httpParams = new BasicHttpParams();
			HttpConnectionParams.setConnectionTimeout(httpParams, Const.CONNECT_HTTP_TIMEOUT);
			HttpConnectionParams.setSoTimeout(httpParams, Const.CONNECT_SOCKET_TIMEOUT);
			HttpClient httpClient = new DefaultHttpClient(httpParams);

			HttpPost httpPost = new HttpPost(url);

			ByteArrayInputStream bais = new ByteArrayInputStream(postdata);

			InputStreamEntity ise = new InputStreamEntity(bais, postdata.length);
			ise.setContentType("binary/octet-stream");
			ise.setChunked(true);
			httpPost.setEntity(ise);


			HttpResponse response = httpClient.execute(httpPost);
			int code = response.getStatusLine().getStatusCode();
			Log.e(tag,"responseCode:"+code);
			HttpEntity entity = response.getEntity();
			Log.e(tag,"length:"+entity.getContentLength());

			StringBuffer strBuf = new StringBuffer();
			if (entity != null) {
				InputStream is = entity.getContent();
				InputStreamReader isr = new InputStreamReader(is, ENCODE);
				BufferedReader br = new BufferedReader(isr);
				String line;
				while ((line = br.readLine()) != null) {
					strBuf.append(line);
				}
				is.close();

				// Consume response content
				entity.consumeContent();

			}
			httpClient.getConnectionManager().shutdown();
			if (strBuf.toString() == null || "".equals(strBuf.toString()))
				return null;
			try {
//				Log.e(tag,"result:"+strBuf.toString());
				JSONObject outer = new JSONObject(strBuf.toString());
				JSONArray pa = outer.getJSONArray("parameters");
				if (pa != null && pa.length() > 0) {
					return pa.getJSONObject(0);
				}
			} catch (JSONException e) {
				Log.e("RequestPost", ":@" + e.getMessage());
				return null;
			}
	
		} catch (SecurityException se) {
			Log.e("RequestPost", "se:@" + se.getMessage());
			return null;
		} catch (InterruptedIOException ie) {
			Log.e("RequestPost", "iioe:@" + ie.getMessage());
			return null;
		} catch (IOException e) {
			Log.e("RequestPost", "ioe:@" + e.getMessage());
			return null;
		} catch (NullPointerException npe) {
			Log.e("RequestPost", "pne:@" + npe.getMessage());
			return null;
		} finally {
			try {
				if (in != null)
					in.close();
				if (out != null)
					out.close();
				if (bos != null)
					bos.close();
				this.stopConnect();
			} catch (IOException ignored) {
				this.stopConnect();
			}
			
		}
		return null;
	}
    
	public Object post2(String content, String url) {
		
        Log.v("url", ":"+url);
        Log.i("req", ":@"+content);
		InputStream in = null;
		OutputStream out = null;
		ByteArrayOutputStream bos = null;
		HttpURLConnection hc;
		try {
			byte[] postdata = content.getBytes(ENCODE);
			
//			HttpParams httpParams = new BasicHttpParams();
//			HttpConnectionParams.setConnectionTimeout(httpParams,
//					Constant.CONNECT_HTTP_TIMEOUT);
//			HttpConnectionParams.setSoTimeout(httpParams,
//					Constant.CONNECT_SOCKET_TIMEOUT);
//			HttpClient httpClient = new DefaultHttpClient(httpParams);
//
//			HttpPost httpPost = new HttpPost(url);
//
//			ByteArrayInputStream bais = new ByteArrayInputStream(postdata);
//
//			InputStreamEntity ise = new InputStreamEntity(bais, postdata.length);
//			ise.setContentType("binary/octet-stream");
//			ise.setChunked(true);
//			httpPost.setEntity(ise);
//            Log.v("Content-Length", ""+postdata.length);
////			httpPost.addHeader("Content-Length", ""+postdata.length);
//			if (DataModel.getSessionId() != null
//					&& !"".equals(DataModel.getSessionId().trim())) {
//				httpPost.addHeader("Cookie", "JSESSIONID="
//						+ DataModel.getSessionId());
//			}
//
////			httpPost.addHeader("X-UserAgent",Constant.UserAgent);
//
//			HttpResponse response = httpClient.execute(httpPost);
//			HttpEntity entity = response.getEntity();
			
			
			URL connUrl = new URL(url);
			hc = (HttpURLConnection) connUrl.openConnection();
			hc.setConnectTimeout(60*1000);
			hc.setReadTimeout(60*1000);
			hc.setDoOutput(true);
			hc.setDoInput(true);
			hc.setRequestMethod("POST");
//			hc.setRequestProperty("Accept","*/*");
//            hc.setRequestProperty("Accept-Language", "zh-CN");
//            hc.setRequestProperty("Charset", "UTF-8");
//            hc.setRequestProperty("User-Agent", "1Store/1.0");
			hc.setRequestProperty("Content-Length", ""+postdata.length);
            hc.setRequestProperty("Connection", "Keep-Alive");
            if (DataModel.getSessionId() != null&& !"".equals(DataModel.getSessionId().trim())) {
            	hc.setRequestProperty("Cookie", "JSESSIONID="+ DataModel.getSessionId());
            }
 
            
            this.startConnect();
			dataProc.getDataTimer().addConnect(this);
			
	
			out = hc.getOutputStream();
			if(postdata.length>0)
			{
				out.write(postdata, 0, postdata.length);
			}
 
			out.flush();
            out.close();
            out = null;
			
			Log.v("code", ""+hc.getResponseCode());
			Log.e(tag,"length:"+hc.getContentLength());
			
			
            if(DataModel.getSessionId()==null || "".equals(DataModel.getSessionId().trim())){
					String headers = hc.getHeaderField("Set-Cookie");
					if(headers != null){
						DataModel.setSessionId(headers);
					}
            }
            Log.v("Cookie", ""+DataModel.getSessionId());

			StringBuffer strBuf = new StringBuffer();
			 
			in = hc.getInputStream();
			InputStreamReader isr = new InputStreamReader(in, ENCODE);
			BufferedReader br = new BufferedReader(isr);
			String line;

			while ((line = br.readLine()) != null) {
				strBuf.append(line);
				
			}
//			int ch;
//			while((ch=in.read())!=-1){
////				Log.v("reading", ""+(char)ch);
//				strBuf.append((char)ch);
//			}
			in.close();
 
		    if(strBuf.toString() == null || "".equals(strBuf.toString()))
		    	return null;
			try {
				Log.i("msg", ":@"+strBuf.toString());
				 return JSONUtil.strToMoliscMessage(strBuf.toString(),"");
			}catch(Exception e){
				
			}
		} catch (SecurityException se) {
		} catch (InterruptedIOException ie) {
			System.out.println(ie.getMessage());
		} catch (IOException e) {
			System.out.println("ioe:" + e.getMessage());
		} catch (NullPointerException ne) {

		} finally {
			try {
				if (in != null)
					in.close();
				if (out != null)
					out.close();
				if (bos != null)
					bos.close();
				this.stopConnect();
			} catch (IOException ignored) {
				this.stopConnect();
			}
		}
		return null;
	}
 

	public static byte[] convertUnicode2UTF8Byte(String s) {
		byte b[];
		byte b1[];
		int len;
		int count = 0;
		char c;
		if (s == null || s.length() == 0)
			return null;
		len = s.length();
		b = new byte[len * 3];
		for (int i = 0; i < len; i++) {
			c = s.charAt(i);
			if (0x0080 > c) {
				b[count++] = (byte) c;
			} else if (0x0800 > c) {
				b[count++] = (byte) ((c >> 6) | 0xc0);
				b[count++] = (byte) ((c & 0x003F) | 0x80);
			} else {
				b[count++] = (byte) ((c >> 12) | 0xE0);
				b[count++] = (byte) (((c & 0x0FC0) >> 6) | 0x80);
				b[count++] = (byte) ((c & 0x003F) | 0x80);
			}
		}
		b1 = new byte[count];
		System.arraycopy(b, 0, b1, 0, count);
		b = null;
		return b1;
	}

	/**
	 * Method description
	 * 
	 */
	public static String convertByteArray2UTF8String(byte[] arrays) {
		if (arrays == null)
			return null;
		ByteArrayInputStream bais = new ByteArrayInputStream(arrays, 0, arrays.length);
		InputStreamReader isreader = null;

		try {
			isreader = new InputStreamReader(bais, "UTF-8");
		} catch (IOException ioe) {

		} catch (Exception exception1) {
			isreader = new InputStreamReader(bais);
		}
		String s;
		StringBuffer stringbuffer = new StringBuffer();
		int i = -1;
		do {
			try {
				if ((i = isreader.read()) == -1) {
					break;
				}
				char c = (char) i;
				if (c == '\n') {
					break;
				}
				if (c != '\r') {
					stringbuffer.append(c);
				}
				continue;
			} catch (IOException ioe) {

			} catch (Exception exception) {

			}
			break;
		} while (true);
		s = stringbuffer.toString();
		{
			try {
				if (isreader != null) {
					isreader.close();
					isreader = null;
				}
				if (bais != null) {
					bais.close();
					bais = null;
				}
			} catch (Exception exception3) {
			}
		}
		if (s.length() == 0) {
			if (i == -1) {
				return null;
			} else {
				return "";
			}
		} else {
			return s;
		}
	}

	private byte[] addCapacity(byte rece[]) {
		byte temp[] = new byte[rece.length + 1024];
		System.arraycopy(rece, 0, temp, 0, rece.length);
		return temp;
	}

}
